//
//  oAuthViewController.swift
//  weibo10
//
//  Created by 晁岳山 on 15/10/16.
//  Copyright © 2015年 晁岳山. All rights reserved.
//

import UIKit
import SVProgressHUD
class oAuthViewController: UIViewController {
    
    private lazy var webView: UIWebView = UIWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view = webView
        webView.delegate = self
        //设置按钮
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        
         self.webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthURL))
        
    }
    //关闭控制器
    @objc private func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    //自动填充密码和用户名
    @objc private func autoFill() {
        let js = "document.getElementById('userId').value = '18865273696';" +
            "document.getElementById('passwd').value = 'XIAOCHOUyu151730';"
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
}
// MARK: - UIWebViewDelegate
extension oAuthViewController: UIWebViewDelegate {
    //获取发送的request 请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        // 1. 判断访问的主机是否是 www.baidu.com
        guard let url = request.URL where url.host == "www.baidu.com" else {
            return true
        }
        // 2. 从百度地址的 url 中提取 `code=` 是否存在
        guard let query = url.query where query.hasPrefix("code=") else {
            print("取消授权")
            self.close()
            return false
        }
        // 3. 从 query 字符串中提取 `code=` 后面的授权码
        let code = query.substringFromIndex("code=".endIndex)
        // 4. 加载 accessToken
        UserAccountViewModel.sharedUserViewMModel.loadAccessToken(code) { (issucced) -> () in
            if issucced {
                print("成功获取token")
                //在跳转页面之前 要把控制器销毁掉在dismiss之后控制器不会立即销毁
                //所以发送通知一定要在控制器被销毁之后  在回调中发送通知
                self.dismissViewControllerAnimated(true, completion: { () -> Void in
                    //授权成功以后发送通知  进入welcome界面
                    NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewControllerNotifycation, object: "welcome")
                })
            } else {
                
                self.close()
                delay(0.5, callBack: { () -> () in
                    SVProgressHUD.showErrorWithStatus("您的网络不给力，请重新尝试登录")
                })
                print("获取token失败")
            }
        }
        return false
    }
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
}